package com.example.wanghao.wangyixinwen.menu;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wanghao.wangyixinwen.PullToRefresh.PullToRefreshBase;
import com.example.wanghao.wangyixinwen.PullToRefresh.PullToRefreshListView;
import com.example.wanghao.wangyixinwen.R;
import com.example.wanghao.wangyixinwen.act.DatailActivity;
import com.example.wanghao.wangyixinwen.adapter.NewItemAdapter;
import com.example.wanghao.wangyixinwen.bean.NewItemBean;
import com.example.wanghao.wangyixinwen.home.BasePage;
import com.example.wanghao.wangyixinwen.utils.CommonUtil;
import com.example.wanghao.wangyixinwen.utils.DensityUtil;
import com.example.wanghao.wangyixinwen.utils.GsonTools;
import com.example.wanghao.wangyixinwen.utils.HMAPI;
import com.example.wanghao.wangyixinwen.utils.SharedPreferenceTools;
import com.example.wanghao.wangyixinwen.view.RollViewPager;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanghao on 2016/5/20.
 */

//新闻界面中根据频道标题对应的页面对象有12个
public class NewItemPage extends BasePage {

    @ViewInject(R.id.lv_item_news)
    private PullToRefreshListView mLv;
    private String mUrl;
    private NewItemAdapter mNewItemAdapter;
    @ViewInject(R.id.dots_ll)
    private LinearLayout dots_ll;//用来展示小圆点的容器
    @ViewInject(R.id.top_news_title)
    private TextView top_news_title;//用来展示轮播图标题
    @ViewInject(R.id.top_news_viewpager)
    private LinearLayout top_news_viewpager;//用来展示轮播图的容器

    private boolean isReFresh;//用来记录下拉刷和加载更多,true下拉刷新
    private Handler mHandler = new Handler() {

        private RollViewPager mRollViewPager;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            isLoad = true;
            if (isReFresh) {
                //获取当前时间并设置给开源控件,并记录
                String currentTime = CommonUtil.getStringDate();
                //设置下拉刷新的时间
                mLv.setLastUpdatedLabel(currentTime);

                SharedPreferenceTools.saveString(mContext, "updateTime", currentTime);
                //动态创建小圆点
                initDots(mNewsTitles.size());
                //当下拉刷新时才需要进行轮播图的限制

                //如果轮播图已经被创建了,就有一个消息正在循环,第二次进行界面刷新的时候,必须把之前清空
                if (mRollViewPager != null) {
                    mRollViewPager.stop();
                }
                //轮播图控件
                mRollViewPager = new RollViewPager(mContext, dots);
                //将标题数据集合和控件交由轮播图viewpager管理
                mRollViewPager.setTitles(mNewsTitles, top_news_title);
                //将热门新闻的图片地址集合交给viewpager管理
                mRollViewPager.setImages(mNewsImages);

                mRollViewPager.setOnClickItemListener(new RollViewPager.OnClickListener() {
                    @Override
                    public void onClick() {
                        Toast.makeText(mContext, "轮播图的点击事件被回调了", Toast.LENGTH_SHORT).show();
                    }
                });
                mRollViewPager.start();
                //在显示新的轮播图时必须把之前的删除,再进行显示
                top_news_viewpager.removeAllViews();
                //将轮播图rollviewpager添加到线性布局中展示
                top_news_viewpager.addView(mRollViewPager);
            }


            //设置适配器
            if (mNewItemAdapter == null) {
                mNewItemAdapter = new NewItemAdapter(mNews, mContext);
                mLv.getRefreshableView().setAdapter(mNewItemAdapter);
            } else {
                mNewItemAdapter.notifyDataSetChanged();
            }
            if (mLv.getRefreshableView().getHeaderViewsCount() == 0) {
                mLv.getRefreshableView().addHeaderView(mTopView);
            }

            //下拉刷新
            mLv.onPullDownRefreshComplete();
            //加载更多
            mLv.onPullUpRefreshComplete();
        }
    };
    private View mTopView;
    private NewItemBean mNewItemBean;
    private String mMoreUrl;

    public NewItemPage(Context context, String url) {
        super(context);
        this.mUrl = url;
    }

    @Override
    public View initView() {
        /*TextView tv = new TextView(mContext);
        tv.setText("新闻条目界面");
        return tv;*/
        View view = View.inflate(mContext, R.layout.frag_item_news, null);
        //ButterKnife.bind(this, view);
        ViewUtils.inject(this, view);
        //mLv = new ListView(mContext);
        mTopView = View.inflate(mContext, R.layout.layout_roll_view, null);
        ViewUtils.inject(this, mTopView);

        mLv.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //将对应条目的标记设为已读
                //方式一
                NewItemBean.DataItem.NewsItem itemAtposition = (NewItemBean.DataItem.NewsItem)
                        mLv.getRefreshableView().getItemAtPosition(position);//获取对应位置数据
                //方式二
               /* int headerViewsCount = mLv.getHeaderViewsCount();
                NewItemBean.DataItem.NewsItem itemAtposition = mNews.get(position-headerViewsCount);
                */

                if (!itemAtposition.isRead) {
                    itemAtposition.isRead = true;
                    mNewItemAdapter.notifyDataSetChanged();
                }

                //将详情url传递到下一个界面
                Intent intent = new Intent(mContext, DatailActivity.class);
                intent.putExtra("url", itemAtposition.url);
                mContext.startActivity(intent);
            }
        });

        //设置下拉刷新是否可用
        mLv.setPullRefreshEnabled(true);
        //设置当前上拉加载更多是否可用
        mLv.setPullLoadEnabled(true);
        //设置到底是否自动加载更多数据
        mLv.setScrollLoadEnabled(false);

        mLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            //下拉刷新的回调方法
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //Toast.makeText(mContext, "下拉刷新", Toast.LENGTH_SHORT).show();
                if (TextUtils.isEmpty(mMoreUrl)) {
                    Toast.makeText(mContext, "已经没有下拉刷新的数据了", Toast.LENGTH_SHORT
                    ).show();
                    mLv.onPullUpRefreshComplete();
                } else {
                    getNewItemData(true, mMoreUrl);
                }

            }

            //加载更多的回调方法
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (TextUtils.isEmpty(mMoreUrl)) {
                    Toast.makeText(mContext, "没有加载更多的新数据了", Toast.LENGTH_SHORT).show();
                    mLv.onPullUpRefreshComplete();
                } else {
                    getNewItemData(false, mMoreUrl);
                }
                // Toast.makeText(mContext, "加载更多", Toast.LENGTH_SHORT).show();
            }
        });
        //设置之前的更新时间
        String updateTime = SharedPreferenceTools.getString(mContext, "updateTime", "");
        mLv.setLastUpdatedLabel(updateTime);
        return view;
    }

    @Override
    public void initData() {
        String result = SharedPreferenceTools.getString(mContext, HMAPI.BASE_URL + mUrl, "");
        if (!TextUtils.isEmpty(result)) {

            parseJson(result, true);
        }
        getNewItemData(true, mUrl);


    }

    //用来区分是下拉刷新还是加载更多,true是下拉刷新,false加载更多
    private void getNewItemData(final boolean isRefresh, String url) {
        Request request = new Request.Builder().url(HMAPI.BASE_URL + url).build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "新闻条目数据获取失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String result = response.body().string();
                parseJson(result, isRefresh);

                SharedPreferenceTools.saveString(mContext, HMAPI.BASE_URL + mUrl, result);
            }
        });
    }

    //新闻列表的数据集合
    private List<NewItemBean.DataItem.NewsItem> mNews = new ArrayList<>();
    //热门新闻的标题
    private List<String> mNewsTitles = new ArrayList<>();
    //热门新闻的图片地址url
    private List<String> mNewsImages = new ArrayList<>();

    //用来区分是下拉刷新还是加载更多,true是下拉刷新,false加载更多
    private void parseJson(String result, boolean isRefresh) {
        this.isReFresh = isRefresh;
        mNewItemBean = GsonTools.changeGsonToBean(result, NewItemBean.class);
        System.out.println(mNewItemBean);
        if (isRefresh) {//下拉刷新需要将旧数据清除,再加载新数据
            //获取新闻列表的数据集合
            mNews.clear();
            mNews.addAll(mNewItemBean.data.news);

            //获取标题与图片数据
            mNewsImages.clear();
            mNewsTitles.clear();
            for (NewItemBean.DataItem.TopnewsItem item :
                    mNewItemBean.data.topnews) {
                mNewsTitles.add(item.title);
                mNewsImages.add(item.topimage);
            }
        } else {//加载更多,旧数据需要展示,新加载的在最后展示
            mNews.addAll(mNewItemBean.data.news);
        }

        //获取more字段,下拉刷新与加载更多的数据在最后显示
        mMoreUrl = mNewItemBean.data.more;


        mHandler.sendEmptyMessage(0);

    }

    //页面指示器,小圆点集合
    private List<ImageView> dots = new ArrayList<>();

    //动态创建轮播图的点
    private void initDots(int size) {
        dots.clear();
        dots_ll.removeAllViews();
        for (int i = 0; i < size; i++) {
            ImageView dot = new ImageView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px
                    (mContext, 5), DensityUtil.dip2px(mContext, 5));


            if (i == 0) {
                dot.setImageResource(R.drawable.dot_focus);
            } else {
                dot.setImageResource(R.drawable.dot_normal);
                params.leftMargin = DensityUtil.dip2px(mContext, 5);
            }
            dot.setLayoutParams(params);

            dots.add(dot);
            //展示在界面上
            dots_ll.addView(dot);
        }

    }

}